package com.liangxy.news.api;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * API client for network requests
 */
public class ApiClient {

    // API密钥默认值
    public static final String DEFAULT_API_KEY = "a7c11514d77b72577a0e238ad5f407af";

    // 添加连接超时和重试逻辑
    private static final int CONNECTION_TIMEOUT = 20; // 增加超时时间到20秒
    private static final int MAX_RETRIES = 3; // 最大重试次数
    private static final String BASE_URL = "http://v.juhe.cn/";
    private static final String PREF_NAME = "api_settings";
    private static final String KEY_API_KEY = "api_key";

    private static Retrofit retrofit = null;
    private static OkHttpClient okHttpClient = null;
    private static String apiKey = DEFAULT_API_KEY;

    /**
     * 初始化ApiClient
     * @param context 上下文
     */
    public static void init(Context context) {
        if (context != null) {
            SharedPreferences preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            apiKey = preferences.getString(KEY_API_KEY, DEFAULT_API_KEY);
        }
    }


    public static String getApiKey() {
        return apiKey;
    }

    public static void saveApiKey(Context context, String newApiKey) {
        if (context != null && newApiKey != null && !newApiKey.isEmpty()) {
            SharedPreferences preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            preferences.edit().putString(KEY_API_KEY, newApiKey).apply();
            apiKey = newApiKey;

            // 重置Retrofit实例，使其在下次调用时重新创建
            retrofit = null;
        }
    }

    /**
     * Get OkHttpClient instance with logging and timeouts
     * @return OkHttpClient instance
     */
    private static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            // 添加日志拦截器，方便调试
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            // 构建OkHttpClient，设置超时和日志
            okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
                    .addInterceptor(loggingInterceptor)
                    .build();
        }
        return okHttpClient;
    }

    private static Retrofit getRetrofit() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(getOkHttpClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

    public static NewsApiService getNewsApiService() {
        return getRetrofit().create(NewsApiService.class);
    }
}